<?php

namespace app\common\controller\zhongzhuanv2;

use app\admin\library\Auth;
use think\Config;
use think\Controller;
use think\Db;
use ec\Ecbase as Eccommon;

/**
 * 后台控制器基类
 */
class Autoassign extends Controller{
    
    
    /**
     * 
     * @param type $request_data
     * $list = [
            array(
                "followUserId" => ,
                "mobile" => 18300000015,
                "name" => "测试数据15",
                "fields"=>[
                    '82705932'=>'C级(明确拒绝)',
                    '82720068'=>'https://byrobot-prod.oss-cn-hangzhou.aliyuncs.com/20240807/20240807NbT05l8528034362_19553058820.mp3'
                ]
            )
        ];
     */
    public static function startAssign($request_data){
        
        $assign_id = empty($request_data['assign_id'])?1:$request_data['assign_id'];
        db('ec_assign_kehu')->where('id',$assign_id)->update(['status'=>1]);
        
        $assign_list = db('ec_assign_kehu')->alias('a')->field('a.id assign_id,u.id ecid,b.id assign_detail_id, b.people,b.success_people,u.userid optUserId,u.name username,u.account,c.yixiang_txt,c.yixiang_value')
                ->join('ec_assign_kehu_detail b','a.id=b.assign_id')
                ->join('ec_ai_task_phone_yixiang c','c.id=b.yixiang_id')
                ->join('ec_user u','b.user_id = u.id')
                ->where('a.id',$assign_id)
                ->select();
        $end_list = [];
        foreach ($assign_list as $value){
            $new_key = $value['yixiang_value'];
            $value['assign_count'] = 0;
            $end_list[$new_key]['count'] = $value['people'] - $value['success_people'] + (empty($end_list[$new_key]['count']) ? 0 : $end_list[$new_key]['count']);
            $end_list[$new_key]['user_list'][] = $value;
        }
        $list = [];
        
        //每一个意向的用户
        foreach ($end_list as $key=>$value){
            $kehu_list = db('ec_ai_task_phone_bak')->field('id byid,customerTelephone,customerName,callInstanceId,yixiang_txt,yixiang_value,startTime')->where([
                'yixiang_value'=>$key,       
                'status'=>0
            ])->limit($value['count'])->order('startTime desc')->select();
            $value['kehu_list'] = $kehu_list;
            $list[$key] = $value;
        }
        
        $assign_end_list = $update_assign_detail = [];
       
        foreach ($list as $value){
            $item_kehu_list = $value['kehu_list'];
            $item_user_list = $value['user_list'];
            foreach ($item_kehu_list as $item_kehu_v){
                $item_result = self::assingSignleKehuToUser($item_kehu_v, $item_user_list);
                $middle_data = $item_result['middle_data'];
                $item_user_list = $item_result['item_user_list'];
                $assign_end_list[] = $middle_data;
              
            }
            
            foreach ($item_user_list as $k =>$v){
                $update_assign_detail[$v['assign_detail_id']] = [
                    'people'=>$v['people'],
                    'success_people'=>$v['assign_count'] + $v['success_people'],
                ];
            }
           
            
        }
        
        
        $all_kehu_id = array_column($assign_end_list, 'byid');
        
        try{
            Db::startTrans();
            
            
            
            
            foreach ($update_assign_detail as $key =>$value){
                $save_data = ['success_people'=>$value['success_people']];               
                db('ec_assign_kehu_detail')->where('id',$key)->update($save_data);
            }
            
            
            $daituisong_count = $assign_info['daituisong_count'] + count($all_kehu_id);
            $assign_info = db('ec_assign_kehu')->where('id',$assign_id)->find();
            $update_assign_data = ['daituisong_count'=>$daituisong_count];
            if($daituisong_count >= $assign_info['count']){
                $update_assign_data['status'] = 2;
            }
            db('ec_assign_kehu')->where('id',$assign_id)->update($update_assign_data);
            
            db('ec_aiuser_to_ecuser')->insertAll($assign_end_list);
            db('ec_ai_task_phone_bak')->where('id','in',$all_kehu_id)->setField('status',1);
            
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
        }
        
        
        
        
        
    }
    
    public static function assingSignleKehuToUser($kehu_item,$user_list){
        $field_id_config = config('zhongzhuan.field');
        $yixiang_field_id = $field_id_config['yixiang']['fieldid'];
        $baiying_luyin_field_id = $field_id_config['baiying_luyin']['fieldid'];
        
        $luyin_domain_prefix = config('zhongzhuan.luyin_domain_prefix');
        $default = 9999999;
        $followUserId = '';
        $followUserId_index = 0;
        foreach ($user_list as $key=>$value){
            if($value['assign_count'] >= ($value['people'] - $value['success_people']))                continue;
            if($value['assign_count'] < $default){
                $followUserId = $value['optUserId'];
                $default = $value['assign_count'];
                $followUserId_index = $key;
            }
        }
        
        $luyinOssUrl = $luyin_domain_prefix . '?callInstanceId='.$kehu_item['callInstanceId'];
        
        $temp_data = [
            "followUserId"=>$followUserId,"mobile"=>$kehu_item['customerTelephone'],"name"=>$kehu_item['customerName'],
            "fields"=>[$yixiang_field_id=>$kehu_item['yixiang_txt'],$baiying_luyin_field_id=>$luyinOssUrl]
        ];
        
        $middle_data = [
            
            "mobile"=>$kehu_item['customerTelephone'],"name"=>$kehu_item['customerName'],"createtime"=>time(),'yixiang_value'=>$kehu_item['yixiang_value'],
            'assign_id'=>$user_list[$followUserId_index]['assign_id'],'ecid'=>$user_list[$followUserId_index]['ecid'],'byid'=>$kehu_item['byid'],'yixiang_txt'=>$kehu_item['yixiang_txt'],"starttime"=>date('Y-m-d H:i:s',$kehu_item['startTime'] / 1000),
            "content"=> json_encode($temp_data,JSON_UNESCAPED_UNICODE)
        ];
        $user_list[$followUserId_index]['assign_count'] =  $user_list[$followUserId_index]['assign_count'] + 1;
        

        
        return ['middle_data'=>$middle_data,'item_user_list'=>$user_list];
        
    }
}
